<?
require_once("ericdingle/model/BaseProvider.php");
require_once("ericdingle/model/photo/PhotoEntity.php");

class PhotoProvider extends BaseProvider {
	public static function getInstance() {
		return parent::getInstance(__CLASS__);
	}
	
	// CRUD
	
	public function create($photo) {
		$photoID = $this->dataInterface_->executeNonQuery(sprintf(
			"INSERT INTO Photo (PhotoID, PostID, Path, Caption) " .
			"VALUES (NULL, %d, '%s', '%s')",
			$photo->getPostID(),
			$this->dataInterface_->sanitize($photo->getPath()),
			$this->dataInterface_->sanitize($photo->getCaption())
		));
		
		$photo->setPostID($photoID);
	}
	
	public function read($photo = null, $orderBy = null, $limit = null) {
		if (!$orderBy) $orderBy = "P.PhotoID ASC";
		
		$result = $this->dataInterface_->executeQuery(
			"SELECT P.PhotoID, P.PostID, P.Path, P.Caption " .
			"FROM Photo P " .
			($photo ? "WHERE " . $this->getConstraints($photo) . " " : "") .
			"ORDER BY $orderBy "
		);
		
		if (!$result) {
			die($this->dataInterface_->getError());
		}
		
		$photos = array();
		while ($row = $this->dataInterface_->getNextRow($result)) {
			array_push($photos, $this->loadEntity($row));
		}
		
		return $photos;
	}
	
	public function update($photo) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"UPDATE Photo " .
			"SET Caption = '%s' " .
			"WHERE PhotoID = %d",
			$this->dataInterface_->sanitize($photo->getCaption()),
			$photo->getPhotoID()
		));
	}
	
	public function delete($photo) {
		$this->dataInterface_->executeNonQuery(sprintf(
			"DELETE FROM P " .
			"USING Photo P " .
			"WHERE " . $this->getConstraints($photo)
		));
	}
	
	// Helpers
	
	private function getConstraints($photo) {
		$constraints = array();
		if ($photoID = $photo->getPhotoID()) {
			array_push($constraints, sprintf("P.PhotoID = %d", $photoID));
		}
		if ($postID = $photo->getPostID()) {
			array_push($constraints, sprintf("P.PostID = %d", $postID));
		}
		return implode(" AND ", $constraints);
	}
	
	private function loadEntity($row) {
		return new PhotoEntity(
			$row["PhotoID"],
			$row["PostID"],
			$row["Path"],
			$row["Caption"]
		);
	}
	
	public function readByPostID($postID) {
		$photo = new PhotoEntity(null, $postID, null, null);
		return $this->read($photo);
	}
	
	public function deleteByPostID($postID) {
		$photo = new PhotoEntity(null, $postID, null, null);
		$this->delete($photo);
	}
}
?>
